//
//  HXTextView.m
//  HXTextView
//
//  Created by 吴红星 on 5/17/16.
//  Copyright © 2016 wuhongxing. All rights reserved.
//

#import "HXTextView.h"

@interface HXTextView ()

@property (nonatomic, strong) UILabel *placeholderLabel;

@end

@implementation HXTextView


- (instancetype)init {
    if (self = [super init]) {
        [self configurDefaultParameter];
        [self configurDefaultAppearence];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self configurDefaultParameter];
        [self configurDefaultAppearence];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self configurDefaultParameter];
        [self configurDefaultAppearence];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange:) name:UITextViewTextDidChangeNotification object:nil];
    }
    return self;
}

- (void)configurDefaultParameter {
    _placeholder      = @"请输入文字";
    _placeholderFont  = [UIFont systemFontOfSize:14];
    _placeholderColor = [UIColor lightGrayColor];
    _borderWidth      = 1;
    _borderColor      = [UIColor blackColor];
    _cornerRadius     = 2;
    _maxHeight        = 100;
}

- (void)configurDefaultAppearence {
    self.layer.borderWidth = _borderWidth;
    self.layer.borderColor = _borderColor.CGColor;
    self.layer.cornerRadius = _cornerRadius;
}


- (void)textViewDidChange:(NSNotification *)notification {
    [self setNeedsDisplay];
    [self invalidateIntrinsicContentSize];
}

- (void)drawRect:(CGRect)rect {
    if (self.text.length) return;
    if (_placeholder.length) {
        [_placeholder drawInRect:CGRectMake(5, 8, rect.size.width, rect.size.height) withAttributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor],
                                                       NSFontAttributeName: [UIFont systemFontOfSize:14]}];
    }
    
}

- (void)setPlaceholder:(NSString *)placeholder {
    _placeholder = placeholder;
    [self setNeedsDisplay];
}

- (CGSize)intrinsicContentSize {
    float width = self.bounds.size.width;
    CGSize result = [self sizeThatFits:CGSizeMake(width, MAXFLOAT)];
    self.bounds = CGRectMake(0, 0, result.width, result.height);
    result = CGSizeMake(width, result.height < _maxHeight ? result.height : _maxHeight);
    UIEdgeInsets insets = [self contentInset];
    [self setContentInset:insets];
    self.contentSize = result;
    return result;
}

- (void)setText:(NSString *)text {
    super.text = text;
}

@end
